package com.utils.annotationWork;

import com.utils.annotation.IsEmail;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Pattern;

public class IsEmailValidated implements ConstraintValidator<IsEmail, String> {
    private String message;
    private boolean isRequire;

    @Override
    public void initialize(IsEmail constraintAnnotation) {
        this.message = constraintAnnotation.message();
        this.isRequire = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) {
        if(Objects.nonNull(o) && isRequire) {
            //非空进行校验
            return Pattern.matches("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-za-z0-9]+((\\.|-)[A-za-z0-9]+)*\\.[A-za-z0-9]+$", o);
        }
        return true;
    }
}
